<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { HandCardAssetApi } from '#/api/spa/handcard/asset';

 import HandCardActionLogForm from './hand-card-action-log-form.vue'
import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { ref, computed, nextTick,watch } from 'vue';
import { $t } from '#/locales';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';

 import { deleteHandCardActionLog, getHandCardActionLogPage } from '#/api/spa/handcard/asset';
import { useHandCardActionLogGridFormSchema, useHandCardActionLogGridColumns } from '../data';
import { isEmpty } from '@vben/utils';

const props = defineProps<{
  cardId?: number // 租户ID（主表的关联字段）
}>()

 const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: HandCardActionLogForm,
  destroyOnClose: true,
});

/** 创建手牌动作记录表（替换/撤销等） */
function handleCreate() {
  if (!props.cardId){
    message.warning("请先选择一个手牌资产!")
    return
  }
  formModalApi.setData({cardId: props.cardId}).open();
}

/** 编辑手牌动作记录表（替换/撤销等） */
function handleEdit(row: HandCardAssetApi.HandCardActionLog) {
  formModalApi.setData(row).open();
}

/** 删除手牌动作记录表（替换/撤销等） */
async function handleDelete(row: HandCardAssetApi.HandCardActionLog) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_process_msg',
  });
  try {
    await deleteHandCardActionLog(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}


const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useHandCardActionLogGridFormSchema(),
  },
  gridOptions: {
  columns: useHandCardActionLogGridColumns(),
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (!props.cardId){
              return []
          }
          return await getHandCardActionLogPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            cardId: props.cardId,
            ...formValues,
          });
        },
      },
    },
  pagerConfig: {
    enabled: true,
  },
  toolbarConfig: {
    refresh: true,
    search: true,
  },
  height: '600px',
  rowConfig: {
    keyField: 'id',
    isHover: true,
  },
  } as VxeTableGridOptions<HandCardAssetApi.HandCardActionLog>,
});

/** 刷新表格 */
async function onRefresh() {
   await gridApi.query();
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.cardId,
  async (val) => {
    if (!val) {
      return;
    }
    await nextTick();
    await onRefresh()
  },
  { immediate: true },
);
</script>

<template>
       <FormModal @success="onRefresh" />
      <Grid table-title="手牌动作记录表（替换/撤销等）列表">
<!--        <template #toolbar-tools>-->
<!--          <TableAction-->
<!--            :actions="[-->
<!--              {-->
<!--                label: $t('ui.actionTitle.create', ['手牌资产']),-->
<!--                type: 'primary',-->
<!--                icon: ACTION_ICON.ADD,-->
<!--                auth: ['spa:hand-card-asset:create'],-->
<!--                onClick: handleCreate,-->
<!--              },-->
<!--            ]"-->
<!--          />-->
<!--        </template>-->
<!--        <template #actions="{ row }">-->
<!--          <TableAction-->
<!--            :actions="[-->
<!--              {-->
<!--                label: $t('common.edit'),-->
<!--                type: 'link',-->
<!--                icon: ACTION_ICON.EDIT,-->
<!--                auth: ['spa:hand-card-asset:update'],-->
<!--                onClick: handleEdit.bind(null, row),-->
<!--              },-->
<!--              {-->
<!--                label: $t('common.delete'),-->
<!--                type: 'link',-->
<!--                danger: true,-->
<!--                icon: ACTION_ICON.DELETE,-->
<!--                auth: ['spa:hand-card-asset:delete'],-->
<!--                popConfirm: {-->
<!--                  title: $t('ui.actionMessage.deleteConfirm', [row.id]),-->
<!--                  confirm: handleDelete.bind(null, row),-->
<!--                },-->
<!--              },-->
<!--            ]"-->
<!--          />-->
<!--        </template>-->
      </Grid>
</template>
